<template>
  <!-- v-bind="$attrs" 保留原组件的所有 props -->
  <!-- v-on="$listeners" 保留原组件的所有 methods -->
  <a-select
    style="width: 100%"
    v-bind="$attrs"
    v-on="$listeners"
    v-model="selectVal"
    :allowClear="allowClear"
    show-search
    option-filter-prop="children"
    @change="selectChange">
    <a-select-option v-for="(item, index) in selectOption" :key="index" :value="item.value">
      {{ item.label }}
    </a-select-option>
  </a-select>
</template>

<script>
// import { listDictData } from '@/api/system-admin/dict-data';

export default {
  name: 'ASelectList',
  components: {},
  props: {
    // 是否需要查询字典
    isHasDict: {
      type: Boolean,
      default: true
    },
    allowClear: {
      type: Boolean,
      default: true
    },
    // 不需要查询字典时传递的选择列表
    defaultOption: {
      type: Array,
      default: () => []
    },
    // 当前值
    value: {
      type: [Number, String, Array],
      default: '',
      required: true
    },
    // 字典名称-用于在码表查询
    optionName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dictOption: []
    };
  },
  computed: {
    selectVal: {
      set(val) {
        // 通过.sync修饰符传值可以使用
        // this.$emit('update:value', val);
        // 通过v-model传值需要触发默认的input事件
        this.$emit('input', val);
      },
      get() {
        let val = '';
        if (typeof this.value === 'number' && !isNaN(this.value)) {
          val = this.value.toString();
        } else {
          val = this.value;
        }
        return val;
      }
    },
    selectOption() {
      return this.isHasDict ? this.dictOption : this.defaultOption;
    }
  },
  mounted() {
    // this.getOption();
  },
  methods: {
    // 获取下拉数据
    getOption() {
      this.$store.dispatch('dictionary', this.optionName).then(data => {
        this.dictOption = data || [];
      });
    },
    selectChange(val) {
      const currentItem = this.selectOption.find(item => item.value === val);
      this.$emit('callback', currentItem);
    }
  }
};
</script>
<style lang="less" scoped>
</style>
